package org.tigris.atlas.beehive;

import java.util.List;

import org.apache.beehive.netui.pageflow.Forward;
import org.apache.beehive.netui.pageflow.PageFlowController;
import org.tigris.atlas.messages.MessageFactory;
import org.tigris.atlas.messages.Messages;
import org.tigris.atlas.messages.MessagesHandler;
import org.tigris.atlas.service.EntityServiceResponse;
import org.tigris.atlas.service.ServiceResponse;
import org.tigris.atlas.web.struts.InputForm;

public abstract class AbstractPageFlowController extends PageFlowController {

	protected void handleMessages(ServiceResponse response) {
		getMessagesHandler().handleMessages( response.getMessages(), getFormClass(), getRequest() );
	}
	
	protected abstract Class getFormClass();
	
	protected void handleMessages(EntityServiceResponse response, InputForm form) {
		MessagesHandler handler = getMessagesHandler();

		// Handle messages from the response
		handler.handleMessages( response.getMessages(), getFormClass(), getRequest() );
		
		if( response.getEntity() == null ) {
			return;
		}
		
		Messages entityMessages = response.getEntity().getAllMessages();
		if (form == null) {
			// Handle messages from the entity if there is no form present
			handler.handleMessages(entityMessages, getFormClass(), getRequest());	
		} else {
			// Use the form to perform any additional processing, including:
			// 1 - Field-level errors
			// 2 - Error ordering
			form.addMessages(entityMessages, getRequest());
			handler.handleMessages(form.getMessages(), getFormClass(), getRequest());
		}
	}
	
	protected void handleMessages(EntityServiceResponse response) {
		handleMessages(response, null);
	}
	
	protected MessagesHandler getMessagesHandler() {
		return MessageFactory.createMessagesHandler();
	}
	
	protected Forward determineForward() {
		List msgs = (List) getRequest().getAttribute(Messages.REQ_ATTR_ERROR_MSGS);
        if (msgs != null && !msgs.isEmpty()) {
        	return new Forward( PageFlowControllerConstants.FORWARD_FAILURE );
        }
        
        return new Forward( PageFlowControllerConstants.FORWARD_SUCCESS );
	}

}
